<template>
  <view class="page index-page rec-bag-pop-page">
    <uni-navbar
      :border="false"
      :fixed="true"
      :height="barHeight"
      :rightWidth="120"
      :leftWidth="120"
      :leftIcon="!isMpWeixinH5"
      titleStyle="color:#fff;fontSize:18px;"
      :bgColor="isWhiteAppBar ? '#FF5500' : 'transparent'"
      :placeholder="false"
      :autoBack="false"
      :backNative="true"
    >
      <template #left>
        <image v-if="isH5 && !isMpWeixinH5" src="../../static/images/back_white2.png" class="back-icon" style="margin-left: -10rpx;"></image>
        <text style="font-size:36rpx;font-weight:bold;color:#fff;">第1集</text>
      </template>
      <template #right>
        <text style="font-size:36rpx;font-weight:bold;color:#fff;">观看记录</text>
      </template>
    </uni-navbar>

    <view
      class="box-1"
      :style="{paddingTop: 0}"
    >
      <view v-if="isLogin" class="inner-cont">
        <swiper class="swiper" 
          circular 
          :vertical="true"
          :current="currentIdx"
          :indicator-dots="false" 
          :autoplay="false" 
          :interval="5000"
          :duration="500"
          @change="swiperChange"
        >
          <swiper-item class="swiper-item" v-for="item in videoList" :key="item.id" @click="clickVideo">
            <view class="swiper-item-dom" :ref="item.id">
             
            </view>
          </swiper-item>
        </swiper>
      </view>
    </view>

    <view class="irght-info" @click="clickVideo">
      <view>three ID：{{curVideoInfo.id}}</view>
      <view>播放中：{{curVideoInfo.isPlaying}}</view>
      <view>静音：{{curVideoInfo.muted}}</view>
      <view>自动播放：{{curVideoInfo.autoplay}}</view>
    </view>
  </view>
</template>

<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.min.css'

import { isMpAlipay, isMpBaidu, isMpToutiao, isMpKuaishou, isH5 } from '@/utils/platform';
import statusBarInfo from '@/pages/welfare/mixins/statusBarInfo'

const app = getApp();
// import { encryptFn } from '@/utils/index'
// import { getRandomInt } from '@/utils/util'

// import { SignNew } from '@/pages/welfare/api/index';
import { serviceMobile, staticHost } from '@/setting';

export default {
  mixins: [ statusBarInfo ],
  computed: {
    curVideoInfo() {
      if (this.currentIdx >= 0) {
        return this.videoList[this.currentIdx];
      }
      return {};
    }
  },
  data() {
    return {
      isMpAlipay,
      isH5,
      contactsMobile: serviceMobile,
      isWhiteAppBar: false,
      staticHost,
      isLogin: true,
      isMpWeixinH5: false,
      videoList: [
        { id: 'v_s1', url: 'https://www.szaluola.com/videos/video-1.mp4', muted: true, autoplay: true, isPlaying: false, dplayer: null },
        { id: 'v_s2', url: 'https://www.szaluola.com/videos/video-2.mp4', muted: true, autoplay: false, isPlaying: false, dplayer: null },
        { id: 'v_s3', url: 'https://www.szaluola.com/videos/video-3.mp4', muted: true, autoplay: false, isPlaying: false, dplayer: null },
        { id: 'v_s4', url: 'https://www.szaluola.com/videos/video-4.mp4', muted: true, autoplay: false, isPlaying: false, dplayer: null },
      ],
      currentIdx: 0,
      cg: 0,
      menuBottom: isMpAlipay ? 16: 0,
    };
  },
  onLoad() {
    let _self = this;
    if (isMpBaidu || isMpAlipay || isMpToutiao || isMpKuaishou) {
      let userInfo = app.globalData.userInfo;

      if (userInfo && userInfo.userId) {
        if (this.$uma && this.$uma.trackEvent) {
          this.$uma.trackEvent('enter_sign', userInfo);
        }
      }
      
      if (!userInfo || !userInfo.userId) {
        setTimeout(() => {
          // 跳转登录
          this.$navigateTo('/pages/login/phone')
        }, 1000)
      }
    }
    
    function ready() {
      console.log('ready 是否是小程序::', window.__wxjs_environment === 'miniprogram');
      if (window.__wxjs_environment === 'miniprogram') {
        // 是小程序环境
        _self.isMpWeixinH5 = true;
      }
    }
    if (isH5) {
      setTimeout(() => {
        if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
          console.log('开始监听window.ev.WeixinJSBridgeReady');
          document.addEventListener('WeixinJSBridgeReady', ready, false)
        } else {
          ready()
        }
      }, 500)
    }
  },
  onShow() {
    if (isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
      let userInfo = app.globalData.userInfo;
      if (userInfo && userInfo.userId) {
        this.isLogin = true;
      } else {
        this.isLogin = false;
      }
    }
     
    setTimeout(() => {
      if (!this.curVideoInfo.dplayer) {
        this.initVideo();
      }
      // this.muted = true;
      // this.playVideo(this.videoList[0].id);
    }, 200)
  },
  options: { styleIsolation: 'shared' },
  methods: {
    initVideo(obj) {
      let curVideo = obj || this.curVideoInfo;

      let video = document.createElement('video')
      //如果需要全屏幕展现播放器需要增加 object-fit: cover;
      video.id = curVideo.id;
      video.style = 'width: 100%; height: 100%;'
      video.setAttribute('playsinline', true) //IOS微信浏览器支持小窗内播放
      video.setAttribute('webkit-playsinline', true) //这个bai属性是ios 10中设置可以让视频在小du窗内播放，也就是不是全屏播放的video标签的一个属性
      video.setAttribute('webkitPlaysinline', true) //这个bai属性是ios 10中设置可以让视频在小du窗内播放，也就是不是全屏播放的video标签的一个属性
      video.setAttribute('x5-video-player-type', 'h5') //安卓 声明启用同层H5播放器 可以在video上面加东西
      let source = document.createElement('source')
      source.type = 'video/mp4'
      source.src = curVideo.url  //设定的流地址
      
      //将播放源添加到video的子级
      video.appendChild(source)
      //挂载到视频容器中
      console.log(this.$refs[curVideo.id]);
      
      this.$refs[curVideo.id][0].$el.appendChild(video)
      
      //获取屏幕宽高计算出需要展现的比例
      let aspectRatio = '16:9'   //默认横屏
      //activityDetail变量是我业务中用到的，请自行根据实际情况做调整
      // if (this.activityDetail.style.mode == 1) {
      //   //如果是竖屏模式，动态计算出设备宽高，设定一个比例
      //   const systemInfo = uni.getSystemInfoSync()
      //   aspectRatio = systemInfo.windowWidth + ':' + systemInfo.windowHeight
      // }
      let videoPlayer = videojs(
        curVideo.id,
        {
          // poster: 'https://img.taomile.cn/icos/1/banner_top.png',
          title: '嘀嘀嘀劳斯莱斯',
          width: '100%',
          height: '100%',
          paddingTop: '0',
          // playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
          autoDisable: true,
          preload: 'none', //auto - 当页面加载后载入整个视频 meta - 当页面加载后只载入元数据 none - 当页面加载后不载入视频
          language: 'zh-CN',
          fluid: true, // 自适应宽高
          muted: false, //  是否静音
          // aspectRatio: aspectRatio, // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          controls: true, //是否拥有控制条 【默认true】,如果设为false ,那么只能通过api进行控制了。也就是说界面上不会出现任何控制按钮
          autoplay: true, //如果true,浏览器准备好时开始回放。 autoplay: "muted", // //自动播放属性,muted:静音播放
          loop: false, // 导致视频一结束就重新开始。 视频播放结束后，是否循环播放
          // techOrder: ['html5', 'flash'], //播放顺序
          techOrder: ['html5'], //播放顺序
          screenshot: true,
          controlBar: {
            volumePanel: {
              //声音样式
              inline: false // 不使用水平方式
            },
            timeDivider: true, // 时间分割线
            durationDisplay: true, // 总时间
            progressControl: true, // 进度条
            remainingTimeDisplay: true, //当前以播放时间
            fullscreenToggle: true, //全屏按钮
            pictureInPictureToggle: true //画中画
          }
        },
        function onloadAfter(){
          this.on('error', () => {
            //请求数据时遇到错误
            console.log('请求数据时遇到错误')
          })
          this.on('stalled', () => {
            //网速失速
            console.log('网速失速')
          })
          this.on('play', () => {
            //开始播放
            console.log('开始播放')
            curVideo.isPlaying = true
          })
          this.on('pause', () => {
            //暂停
            console.log('暂停')
            curVideo.isPlaying = false
          })

          this.on('ended', () => {
            videojs.log('Awww...over so soon?!');
          });

          this.on('timeupdate',  () => {})
          this.play();
        }
      )
      curVideo.dplayer = videoPlayer;
    },
    swiperChange(e) {
      if (e.detail.current >=0) {
        let list = this.videoList
        console.log('this.curVideoInfo.dplayer.pause > ', this.curVideoInfo.dplayer.pause);
        if (this.curVideoInfo.dplayer) {
          this.curVideoInfo.dplayer.pause()
        }
        console.log('this.curVideoInfo.dplayer.pause > ', 333);
        this.currentIdx = e.detail.current; 

        let obj = this.videoList[this.currentIdx]
        if (!obj.dplayer) {
          console.log('this.curVideoInfo.dplayer.pause > ', 444);
          this.initVideo(obj);
        } else {
          obj.dplayer.play();
        }
      }
    },
    playVideo() {
      let dplayer = this.curVideoInfo.dplayer
      if (dplayer) {
        dplayer.play();
      }
    },
    stopVideo() {
      let dplayer = this.curVideoInfo.dplayer
      if (dplayer) {
        dplayer.pause();
      }
    },
    clickVideo() {
      let current = this.videoList[this.currentIdx]
      console.log('clickVideo > ', current);

      if (current) {
        current.muted = false;
        if (current.isPlaying) {
          this.stopVideo(current.id)
        } else {
          this.playVideo(current.id)
        }
      }
    },
    onPlay(e) {
      console.log('onPlay>' ,e );
      this.videoList[this.currentIdx].isPlaying = true;
    },
    onPause(e) {
      console.log('onPause>' ,e );
      this.videoList[this.currentIdx].isPlaying = false;
    },
    onEnded(e) {
      console.log('onEnded>' ,e );
      let list = this.videoList
      if (this.currentIdx == list.length -1) {
        this.currentIdx = 0;
      } else {
        this.currentIdx = this.currentIdx + 1;
      }
    },
    progressEv(e) {
      // console.log('progressEv>' ,e );
    },
    seekedEv(e) {
      console.log('seekedEv>' ,e );
    },
    onSeeking(e) {
      console.log('onSeeking>' ,e );
    },
    timeupdateEv(e) {
      // console.log('timeupdateEv>' ,e );
    },
    
    toLogin() {
      this.$navigateTo('/pages/login/phone')
    },
    toCoinDetails() {
      this.$navigateTo('/pages/welfare/coinDetails')
    },
    toMyCoin() {
      // this.common.routerPush('/myCoin')
    },
    scrollEv(e) {
      let scrollTop =  e.target.scrollTop
    },
  },
};
</script>
<style lang="scss" scoped>
  .index-page {
    width: 100%;
    background-color: #fff;
    overflow: hidden;
    height: 100%;

    v-deep .u-swiper {
      margin-left: 0;
    }

    .irght-info {
      position: fixed;
      right: 0;;
      top:160px;
      background: #f50;
      color: #fff;
      z-index: 10000;
    }

    .box-1 {
      position: relative;
      margin-bottom: 16rpx;
      background: linear-gradient(180deg,#f50,#F9EEE7);
      height: 100%;
      

      .inner-cont {
        position:relative;
        width: 100%;
        height: 100%;

        .swiper {
          width: 100%;
          height: 100%;
        }
      }

      .swiper-item {
        width: 100vw;
        height: 100%;

        .swiper-item-dom {
          position: relative;
          width: 100%;
          height: 100%;
          padding-top: 0!important;
        }
        

        .item-video {
          width: 100%;
          height: 100%;
        }
      }

      // .withdraw-btn {
      //   margin-left:48rpx;
      //   margin-top: 32rpx;
      //   width:126rpx;
      //   height:48rpx;
      //   line-height:48rpx;
      //   border: 1px solid #fff;
      //   border-radius: 24rpx;
      //   text-align: center;
      //   color:#fff;
      // }
      .ic-box-money {
        position: absolute!important;
        top: 0rpx;
        right: 0;
        width: 332rpx;
      }
    }
  }
</style>

<style lang="scss">

// .vjs-fluid{ /* 给.vjs-fluid设置字体大小以统一各浏览器样式表现，因为video.js采用的是em单位 */
//   font-size: 14px;
// }
// .vjs-fluid button{
//   outline: none;
// }
// .vjs-fluid.vjs-fluid,
// .vjs-fluid.vjs-16-9,
// .vjs-fluid.vjs-4-3{ /* 视频占满容器高度 */
//   height: 100%;
//   background-color: #161616;
// }
// .vjs-poster{
//   background-color: #161616;
// }
// .vjs-fluid .vjs-big-play-button{ /* 中间大的播放按钮 */
//   font-size: 2.5em;
//   line-height: 2.3em;
//   height: 2.5em;
//   width: 2.5em;
//   -webkit-border-radius: 2.5em;
//   -moz-border-radius: 2.5em;
//   border-radius: 2.5em;
//   background-color: rgba(115,133,159,.5);
//   border-width: 0.12em;
//   margin-top: -1.25em;
//   margin-left: -1.75em;
// }
// .vjs-fluid.vjs-paused .vjs-big-play-button{ /* 视频暂停时显示播放按钮 */
//   display: block;
// }
// .vjs-fluid.vjs-error .vjs-big-play-button{ /* 视频加载出错时隐藏播放按钮 */
//   display: none;
// }
// .vjs-loading-spinner { /* 加载圆圈 */
//   font-size: 2.5em;
//   width: 2em;
//   height: 2em;
//   border-radius: 1em;
//   margin-top: -1em;
//   margin-left: -1.5em;
// }
// .vjs-fluid .vjs-control-bar{ /* 控制条默认显示 */
//   display: flex;
// }
// .vjs-fluid .vjs-time-control{display:block;}
// .vjs-fluid .vjs-remaining-time{display: none;}
 
// .vjs-button > .vjs-icon-placeholder:before{ /* 控制条所有图标，图标字体大小最好使用px单位，如果使用em，各浏览器表现可能会不大一样 */
//   font-size: 22px;
//   line-height: 1.9;
// }
// .vjs-fluid .vjs-playback-rate .vjs-playback-rate-value{
//   line-height: 2.4;
//   font-size: 18px;
// }
// /* 进度条背景色 */
// .vjs-fluid .vjs-play-progress{
//   color: #ffb845;
//   background-color: #ffb845;
// }
// .vjs-fluid .vjs-progress-control .vjs-mouse-display{
//   background-color: #ffb845;
// }
// .vjs-mouse-display .vjs-time-tooltip{
//   padding-bottom: 6px;
//   background-color: #ffb845;
// }
// .vjs-fluid .vjs-play-progress .vjs-time-tooltip{
//   display: none!important;
// }
// .v_s1-dimensions.vjs-fluid:not {
//   padding: 0!important;
// }
</style>